package com.flyduck.security.service;

import com.flyduck.security.dto.AppUser;
import com.flyduck.security.entity.AutoRole;
import com.flyduck.security.entity.AutoUser;
import com.flyduck.security.mapper.ManualUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 *
 * @author flyduck 2021/7/5
 * @version V1.0
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify by user: flyduck 2021/7/5
 * @modify by reason:{方法名}:{原因}
 **/
@Service
public class UserServiceImpl implements UserService {

    private static final String ROLE_PREFIX = "ROLE_{0}";

    @Autowired
    private ManualUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        AutoUser user = userMapper.getByUserName(userName);
        if (user == null) {
            throw new UsernameNotFoundException(MessageFormat.format("The user is not exist for the user name {0}", userName));
        }

        // TODO 从数据库中获取用户的角色权限
        /*
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
        grantedAuthorityList.add(grantedAuthority);
        */
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        List<AutoRole> roles = userMapper.getRoles(user.getId());
        for (AutoRole role : roles) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(MessageFormat.format(ROLE_PREFIX, role.getRoleName()));
            grantedAuthorityList.add(grantedAuthority);
        }

        AppUser appUser = new AppUser(user.getUserName(), user.getPassword(), grantedAuthorityList, user.getId());
        return appUser;
    }
}
